package com.open.loan.controller;

import java.io.IOException;
import java.util.Date;	
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.open.loan.domain.req.AlipayModel;
import com.open.loan.domain.req.Apply_info;
import com.open.loan.domain.req.Basic_info;
import com.open.loan.domain.req.ReqCreditCardModel;
import com.open.loan.utils.HttpUtil;
import com.open.loan.utils.ResponseUtil;
import com.open.system.domain.LoanAlipayCreditDO;
import com.open.system.domain.LoanBankDO;
import com.open.system.domain.LoanUserDO;
import com.open.system.service.LoanAlipayCreditService;
import com.open.system.service.LoanApplyService;
import com.open.system.service.LoanBankService;
import com.open.system.service.LoanJuxinliPostInfoService;
import com.open.system.service.LoanJuxinliReportService;
import com.open.system.service.LoanUserService;

@RestController
@RequestMapping("/moblie")
public class VueAlipayAndCreditCardController {
	
	public static String client_secret="a0d730a9ebb4411f881b52f5e6d5361a";
	public static String access_token="6aa02e8304cc4ed0abe34b111bf5354f";
	
	@Autowired
	private LoanUserService loanUserService;
	
	@Autowired
	private LoanBankService loanBankService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanJuxinliReportService loanJuxinliReportService;
	
	@Autowired
	private LoanJuxinliPostInfoService loanJuxinliPostInfoService;
	
	@Autowired
	private LoanAlipayCreditService loanAlipayCreditService;
	
	/*@Qualifier("restTemplate")
	@Autowired
	private RestTemplate restTemplate;*/
	
	@GetMapping("/alipay")
	public ResponseEntity<String> alipay(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
		if(loanUserDo==null){
			ResponseUtil.toWrite("100","请重新登录",null, response);
			return null;
		}
		Map<String,Object>bankMap=new HashMap<String,Object>();
		bankMap.put("userId", loanUserDo.getId());
		List<LoanBankDO>banks=loanBankService.list(bankMap);
		LoanBankDO bankDO=null;
		if(banks!=null && banks.size()>0){
			bankDO=banks.get(0);
		}else {
			ResponseUtil.toWrite("103","请先实名认证",null, response);
			return null;
		}
		List<LoanAlipayCreditDO>alipayCreditDO=loanAlipayCreditService.list(bankMap);
		LoanAlipayCreditDO alipay=null;
		boolean hasUpdate=true;
		if(alipayCreditDO!=null && alipayCreditDO.size()>0){
			alipay=alipayCreditDO.get(0);
			hasUpdate=true;
		}else {
			alipay=new LoanAlipayCreditDO();
			hasUpdate=false;
		}
		alipay.setUserId(bankDO.getUserId());
		alipay.setRealName(bankDO.getRealName());
		/*RestTemplate restTemplate=new RestTemplate();*/
		//开始采集获取token==============================
		String url="https://www.juxinli.com/orgApi/rest/v1/alipay/applications/juying";
		AlipayModel model=new AlipayModel();
		Basic_info basic=new Basic_info();
		Apply_info apply=new Apply_info();
		basic.setCell_phone_num(bankDO.getMoblie());
		basic.setId_card_num(bankDO.getIdNo());
		basic.setName(bankDO.getRealName());
		apply.setBasic_info(basic);
		model.setApply_info(apply);
		System.out.println(JSON.toJSONString(model));
		
		 	/*HttpHeaders headers = new HttpHeaders();
	        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	        headers.setContentType(type);
	        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
	        HttpEntity<String> httpEntity = new HttpEntity<String>(JSON.toJSONString(model), headers);
	        Object returnJson = restTemplate.postForObject(url, httpEntity, Object.class);*/
	        
		Object returnJson=HttpUtil.sendPostJsonData(url,JSON.toJSONString(model));
		if(returnJson==""){
			ResponseUtil.toWrite("202","服务器超时，请重新尝试刷新",null, response);
			return null;
		}
		System.out.println(returnJson);//字段1
		JSONObject jsonObject =JSONObject.parseObject(returnJson.toString().replace("=", ":"));
		if("true".equals(jsonObject.getString("success"))){
			String data=jsonObject.getString("data");
			JSONObject jsonData =JSONObject.parseObject(data.toString());
			String token=jsonData.getString("token");//字段2
			String cell_phone_num=jsonData.getString("cell_phone_num");//字段3
			System.out.println(token);
			System.out.println(cell_phone_num);
			alipay.setAlipayRemark1(token);
			alipay.setAlipayRemark2(data);
			//提交采集开始=================================
			String caijiUrl="https://www.juxinli.com/orgApi/rest/v1/alipay/message/collect/req/juying";
			Map<String,String>caijiMap=new HashMap<String,String>();
			caijiMap.put("token",token);
			/*HttpEntity<String> httpEntityCaiji = new HttpEntity<String>(JSON.toJSONString(caijiMap), headers);
	        Object returnCaijiJson = restTemplate.postForObject(caijiUrl, httpEntityCaiji, Object.class);*/
			Object returnCaijiJson=HttpUtil.sendPostJsonData(caijiUrl,JSON.toJSONString(caijiMap));
			System.out.println(returnCaijiJson);//字段2
			JSONObject jsonCaijiObject =JSONObject.parseObject(returnCaijiJson.toString().replace("=", ":"));
			if("true".equals(jsonCaijiObject.getString("success"))){
				String caijiData=jsonCaijiObject.getString("data");
				JSONObject jsonCaijiData =JSONObject.parseObject(caijiData.toString());
				String caijiToken=jsonCaijiData.getString("token");//字段2
				String caijiPhone=jsonCaijiData.getString("cell_phone_num");//字段3
				String process_code=jsonCaijiData.getString("process_code");
				String contentcaiji=jsonCaijiData.getString("content");
				System.out.println(caijiToken);
				System.out.println(caijiPhone);
				System.out.println(process_code);
				System.out.println(contentcaiji);
				Map<String,Object>ReturnCode1=new HashMap<String,Object>();
				ReturnCode1.put("token", caijiToken);
				ReturnCode1.put("processCode", process_code);
				ReturnCode1.put("contentCode", contentcaiji);
				alipay.setAlipayRemark3(caijiData);
				alipay.setAlipayRemark4(contentcaiji);
				if(hasUpdate){
					loanAlipayCreditService.update(alipay);
				}else {
					loanAlipayCreditService.save(alipay);
				}
				
				if("10111".equals(process_code)){
					ResponseUtil.toWrite("200",jsonObject.getString("message"),ReturnCode1, response);
					//alipayThread(caijiToken, request, response);
					return null;
				}else if ("10112".equals(process_code)) {
					ResponseUtil.toWrite("202","二维码已失效,请重新生成",null, response);
					return null;
				}else if ("10008".equals(process_code)) {
					ResponseUtil.toWrite("200","认证成功！",null, response);
					return null;
				}else if ("30000".equals(process_code)) {
					ResponseUtil.toWrite("202","网络异常等非接口可控的错误信息",null, response);
					return null;
				}
			}else {
				ResponseUtil.toWrite("202",jsonCaijiObject.getString("message"),null, response);
				return null;
			}
			//提交采集结束=================================
			
		}else {
			ResponseUtil.toWrite("202",jsonObject.getString("message"),null, response);
			return null;
		}
		//================================================
		return null;
	}
	
	@GetMapping("/alipayThread/{token}")
	 public ResponseEntity<String> alipayThread(@PathVariable String token,HttpServletRequest request,HttpServletResponse response){
			HttpSession session = request.getSession();
			LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
			if(loanUserDo==null){
				ResponseUtil.toWrite("100","请重新登录",null, response);
				return null;
			}
			Map<String,Object>alipayMap=new HashMap<String,Object>();
			alipayMap.put("userId", loanUserDo.getId());
			List<LoanAlipayCreditDO>alipayCreditDO=loanAlipayCreditService.list(alipayMap);
			LoanAlipayCreditDO alipay=null;
			boolean hasUpdate=true;
			if(alipayCreditDO!=null && alipayCreditDO.size()>0){
				alipay=alipayCreditDO.get(0);
				hasUpdate=true;
			}else {
				alipay=new LoanAlipayCreditDO();
				hasUpdate=false;
			}
			//返回二维码=======================================
			String CodeUrl="https://www.juxinli.com/orgApi/rest/v1/alipay/messages/qrcodeCollect/resp/";
			Map<String,String>codeMap=new HashMap<String,String>();
			codeMap.put("token",token);
			/*HttpEntity<String> httpEntityCode = new HttpEntity<String>(JSON.toJSONString(codeMap), headers);
	        Object returnCodeJson = restTemplate.postForObject(CodeUrl, httpEntityCode, Object.class)*/;
			Object returnCodeJson=HttpUtil.sendPostJsonData(CodeUrl,JSON.toJSONString(codeMap));
			System.out.println(returnCodeJson);//字段2
			JSONObject jsonCodeObject =JSONObject.parseObject(returnCodeJson.toString());
			alipay.setAlipayRemark5(jsonCodeObject.toJSONString());
			if("true".equals(jsonCodeObject.getString("success"))){
				String dataCode=jsonCodeObject.getString("data");
				alipay.setAlipayRemark6(dataCode);
				JSONObject jsonCodeData =JSONObject.parseObject(dataCode.toString());
				String Codetoken=jsonCodeData.getString("token");//字段2
				String CodePhone=jsonCodeData.getString("cell_phone_num");//字段3
				String processCode=jsonCodeData.getString("process_code");
				String contentCode=jsonCodeData.getString("content");
				alipay.setAlipayRemark7(processCode);
				alipay.setAlipayRemark8(contentCode);
				if(hasUpdate){
					loanAlipayCreditService.update(alipay);
				}else {
					loanAlipayCreditService.save(alipay);
				}
				System.out.println(Codetoken);
				System.out.println(CodePhone);
				System.out.println(processCode);
				System.out.println(contentCode);
				Map<String,Object>ReturnCode=new HashMap<String,Object>();
				ReturnCode.put("processCode", processCode);
				ReturnCode.put("contentCode", contentCode);
				/*ResponseUtil.toWrite("200",jsonCodeObject.getString("message"),ReturnCode, response);
				return null;*/
				if("10111".equals(processCode)){
					ResponseUtil.toWrite("10111","请再次扫二维码",ReturnCode, response);
					//alipayThread(caijiToken, request, response);
					return null;
				}else if ("10112".equals(processCode)) {
					ResponseUtil.toWrite("202","二维码已失效,请重新生成",null, response);
					return null;
				}else if ("10008".equals(processCode)) {
					ResponseUtil.toWrite("200","认证成功！",null, response);
					return null;
				}/*else if ("30000".equals(processCode)) {
					ResponseUtil.toWrite("202","网络异常等非接口可控的错误信息",null, response);
					return null;
				}*/
				else {
					ResponseUtil.toWrite("202","网络异常等非接口可控的错误信息",null, response);
					return null;
				}
			}else {
				ResponseUtil.toWrite("202",jsonCodeObject.getString("message"),null, response);
				return null;
			}
			//返回二维码===========================================
	    }
	
	//========================================信用卡========================================================
	//====================================信用卡==============================================
	
	
	/*@PostMapping("/creditcard")
	public void creditcard(@RequestBody ReqCreditCardModel reModel ,HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println("-------从新跳转类------");
		response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
        response.setDateHeader("Expires", 0); // Proxies.
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
        response.setHeader("Access-Control-Allow-Credentials","true");
		response.sendRedirect("http://admin.ztamc001.com/moblie/QQInfo?emile="+reModel.getEmail()+"&pass="+reModel.getPassword()+"&dlPass="+reModel.getIdentity());;
	}*/
	
	@RequestMapping(value ="/creditcard",method = RequestMethod.POST)
	public ResponseEntity<String> creditcard2(@RequestBody ReqCreditCardModel model,
			HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
		//LoanUserDO loanUserDo=loanUserService.get(969L);
		if(loanUserDo==null){
			ResponseUtil.toWrite("100","请重新登录",null, response);
			return null;
		}
		Map<String,Object>bankMap=new HashMap<String,Object>();
		bankMap.put("userId", loanUserDo.getId());
		List<LoanBankDO>banks=loanBankService.list(bankMap);
		LoanBankDO bankDO=null;
		if(banks!=null && banks.size()>0){
			bankDO=banks.get(0);
		}else {
			ResponseUtil.toWrite("103","请先实名认证",null, response);
			return null;
		}
		
		List<LoanAlipayCreditDO>alipayCreditDO=loanAlipayCreditService.list(bankMap);
		LoanAlipayCreditDO credit=null;
		boolean hasUpdate=true;
		if(alipayCreditDO!=null && alipayCreditDO.size()>0){
			credit=alipayCreditDO.get(0);
			hasUpdate=true;
		}else {
			credit=new LoanAlipayCreditDO();
			hasUpdate=false;
		}
		credit.setUserId(bankDO.getUserId());
		credit.setRealName(bankDO.getRealName());
		String url="https://www.juxinli.com/orgApi/rest/v4/creditcard/applications/juying";
		Map<String,Object>map=new HashMap<String,Object>();
		Basic_info basic=new Basic_info();
		Apply_info apply=new Apply_info();

		basic.setCell_phone_num(bankDO.getMoblie());
		basic.setId_card_num(bankDO.getIdNo());
		basic.setName(bankDO.getRealName());
		apply.setBasic_info(basic);
		map.put("apply_info", apply);
		map.put("email",model.getEmail());
		map.put("password",model.getPassword());
		map.put("identity",model.getIdentity());
		System.out.println(JSON.toJSONString(map));
		Object returnJson=HttpUtil.sendPostJsonData(url,JSON.toJSONString(map));
		System.out.println(returnJson);//字段1
		JSONObject jsonObject =JSONObject.parseObject(returnJson.toString());
        String token= "";
        credit.setCreditRemark1(returnJson.toString());
		if("true".equals(jsonObject.getString("success"))){
			String data=jsonObject.getString("data");
			credit.setCreditRemark2(data);
			jsonObject = JSONObject.parseObject(data.toString());
			token = jsonObject.getString("token");//字段2
			credit.setCreditRemark3(token);
			String cell_phone_num = jsonObject.getString("cell_phone_num");//字段3
			System.out.println(token);
			System.out.println(cell_phone_num);
			
			String url2="https://www.juxinli.com/orgApi/rest/v4/creditcard/message/collect/req/juying";
			Map<String,String>map2=new HashMap<String,String>();
			map2.put("token", token);
			map2.put("password",model.getPassword());
			map2.put("identity",model.getIdentity());
			map2.put("type", "");
			System.out.println(JSON.toJSONString(map2));
			Object returnJson2=HttpUtil.sendPostJsonData(url2,JSON.toJSONString(map2));
			System.out.println(returnJson2);//字段1
			JSONObject jsonObject2 =JSONObject.parseObject(returnJson2.toString());
			credit.setCreditRemark4(jsonObject2.toJSONString());
			if("true".equals(jsonObject2.getString("success"))){
				String data2=jsonObject2.getString("data");
				JSONObject jsonObject3 = JSONObject.parseObject(data2.toString());
				credit.setCreditRemark5(data2);
				if(hasUpdate){
					loanAlipayCreditService.update(credit);
				}else {
					loanAlipayCreditService.save(credit);
				}
				//ResponseUtil.toWrite("200","接口调用成功",data2, response);
				//ResponseUtil.toWrite("200","接口调用成功",jsonObject3.getString("token"), response);

		        response.setCharacterEncoding("UTF-8");
		        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
		        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		        response.setDateHeader("Expires", 0); // Proxies.
		        response.setHeader("Access-Control-Allow-Origin", "*");
		        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		        response.setHeader("Access-Control-Max-Age", "3600");
		        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
		        response.setHeader("Access-Control-Allow-Credentials","true");
				try {
					response.setContentType("text/html;charset=utf-8");
					JSONObject jsonNode = new JSONObject(new LinkedHashMap());
					jsonNode.put("code", "200");
					jsonNode.put("msg", "接口调用成功");
					jsonNode.put("token", jsonObject3.getString("token"));
					jsonNode.put("data",data2);
					response.getWriter().write(jsonNode.toString());
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}else {
				ResponseUtil.toWrite("202",jsonObject2.getString("message"),null, response);
				return null;
			}
		}else {
			ResponseUtil.toWrite("202",jsonObject.getString("message"),null, response);
			return null;
		}
	}
	
	@PostMapping(value = "/creditcardRetrunInfo/{token}")
	public ResponseEntity<String> creditcardRetrunInfo(@PathVariable String token,HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession();
		LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
		//LoanUserDO loanUserDo=loanUserService.get(969L);
		if(loanUserDo==null){
			ResponseUtil.toWrite("100","请重新登录",null, response);
			return null;
		}
		Map<String,Object>bankMap=new HashMap<String,Object>();
		bankMap.put("userId", loanUserDo.getId());
		List<LoanBankDO>banks=loanBankService.list(bankMap);
		LoanBankDO bankDO=null;
		if(banks!=null && banks.size()>0){
			bankDO=banks.get(0);
		}else {
			ResponseUtil.toWrite("103","请先实名认证",null, response);
			return null;
		}
		List<LoanAlipayCreditDO>alipayCreditDO=loanAlipayCreditService.list(bankMap);
		LoanAlipayCreditDO credit=null;
		boolean hasUpdate=true;
		if(alipayCreditDO!=null && alipayCreditDO.size()>0){
			credit=alipayCreditDO.get(0);
			hasUpdate=true;
		}else {
			credit=new LoanAlipayCreditDO();
			hasUpdate=false;
		}
		String url="https://www.juxinli.com/orgApi/rest/v4/creditcard/messages/qrcodeCollect/resp/";
		Map<String,String>map=new HashMap<String,String>();
		map.put("token", token);
		System.out.println(JSON.toJSONString(map));
		Object returnJson=HttpUtil.sendPostJsonData(url,JSON.toJSONString(map));
		System.out.println(returnJson);//字段1
		JSONObject jsonObject =JSONObject.parseObject(returnJson.toString());
		if("true".equals(jsonObject.getString("success"))){
			String data=jsonObject.getString("data");
			credit.setCreditRemark6(jsonObject.toJSONString());
			credit.setCreditRemark7(data);
			if(hasUpdate){
				loanAlipayCreditService.update(credit);
			}else {
				loanAlipayCreditService.save(credit);
			}
			if(StringUtils.isEmpty(data)){
				ResponseUtil.toWrite("201","认证返回数据为空",data, response);
				return null;
			}
			JSONObject dataJson = JSONObject.parseObject(data.toString());
			String process_code=dataJson.getString("process_code");//字段2
			if("10008".equals(process_code)){
				ResponseUtil.toWrite("200","认证成功",data, response);
				return null;
			}else if ("10003".equals(process_code)) {
				ResponseUtil.toWrite("202","密码错误",null, response);
				return null;
			}else if ("10005".equals(process_code)) {
				ResponseUtil.toWrite("202","独立密码错误",null, response);
				return null;
			}else if ("10111".equals(process_code)) {
				ResponseUtil.toWrite("201","二维码已授权",null, response);
				return null;
			}else if ("10112".equals(process_code)) {
				ResponseUtil.toWrite("202","二维码已失效",null, response);
				return null;
			}else if ("10013".equals(process_code)) {
				ResponseUtil.toWrite("202","您需要打开qq安全中心进行确认",null, response);
				return null;
			}else if ("10016".equals(process_code)) {
				ResponseUtil.toWrite("202","打开微信安全中心公众号进行确认",null, response);
				return null;
			}else if ("30000".equals(process_code)) {
				ResponseUtil.toWrite("202","网络异常",null, response);
				return null;
			}
		}else {
			ResponseUtil.toWrite("202",jsonObject.getString("message"),null, response);
			return null;
			
		}
		return null;
	}
	
}
